package com.xh.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * description: WSServerInitializer <br>
 * date: 2021/11/14 1:22 <br>
 * author: xiehui <br>
 * version: 1.0 <br>
 */

public class WSServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();

        //websocket基于http协议，所需要的http编解码器
        pipeline.addLast(new HttpServerCodec());

        //在http上有一些数据流产生，有大有小，需要使用netty对大数据流写支持
        pipeline.addLast(new ChunkedWriteHandler());

        // 对httpmessage 进行聚合处理，聚合成 request  和  response
        pipeline.addLast(new HttpObjectAggregator(1024*64));

        // 对于websocket，都是以frames进行传输的，不同数据类型frames也不同
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

        // 自定义handler
        pipeline.addLast(new ChatHandler());

    }
}
